import { omit } from 'lodash-unified'
import { defineStore } from 'pinia'
import { reactive, toRefs } from 'vue'
import type { RouteRecordRaw } from 'vue-router'

import { ROUTE } from '@/constants'
import { DefaultLayout, ParentLayout } from '@/layout'
import { constRoutes } from '@/router'

import store from '.'

const routeComponents = import.meta.glob('../views/**/index.tsx')

const loadComponent = (component: string) =>
  routeComponents[`../views/${component}/index.tsx`]

export const usePermissionStore = defineStore('permission', () => {
  const state = reactive({
    routes: [] as RouteRecordRaw[],
    matched: [] as string[]
  })

  async function generate(menus: IUserMenu[]) {
    const list: any[] = []

    // 填充路由组件和路由名称
    for (const menu of menus) {
      const item = { ...menu }

      if (menu.component === 'DefaultLayout') {
        item.component = DefaultLayout
      } else if (menu.component === 'ParentLayout') {
        item.component = ParentLayout
      } else {
        const component = loadComponent(menu.component)
        const module: any = await component()

        item.name = module.default.name
        item.component = component
      }

      list.push(item)
    }

    // 列表转树形
    const hash = new Map<string, any>()
    const tree = [] as any[]

    list.forEach(v => {
      hash.set(v.key, v)
      const parent = hash.get(v.parentKey)
      const route = omit(v, ['key', 'parentKey'])

      if (!parent) {
        tree.push(route)
      } else {
        parent.children.push(route)
      }
    })

    const accessedRoutes: RouteRecordRaw[] = tree

    accessedRoutes.push({
      path: '/:pathMatch(.*)*',
      redirect: {
        path: ROUTE.ERROR,
        query: { status: 404 }
      }
    })

    state.routes = constRoutes.concat(accessedRoutes)

    return accessedRoutes
  }

  return {
    ...toRefs(state),
    generate
  }
})

export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
